package com.itheima.demo07newdatetimeapi;

import org.junit.Test;

import java.time.*;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjuster;

public class Demo01 {

    //日期的值获取
    @Test
    public void test01() {
        // 创建指定日期
        LocalDate fj = LocalDate.of(1985, 9, 23);
        System.out.println("fj = " + fj); // 1985-09-23

        //获取当前日期
        LocalDateTime now = LocalDateTime.now();
        System.out.println(now.getMonth());
        System.out.println("纳秒"+now.getNano());
    }

    //日期的加减
    @Test
    public void test02() {
        //修改日期时间
        LocalDateTime localDateTime = LocalDateTime.now().withDayOfMonth(3);
        System.out.println(localDateTime);
        localDateTime = localDateTime.plusMonths(2);
        localDateTime.minusSeconds(3);
    }

    //日期时间比较
    @Test
    public void test03() {
        LocalDate now = LocalDate.now();
        LocalDate date = LocalDate.of(2018, 8, 8);
        System.out.println(now.isBefore(date)); // false
        System.out.println(now.isAfter(date)); // true
    }

    // 日期格式化
    @Test
    public void test04() {
        // 得到当前日期时间
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String dateTime = formatter.format(now);
        LocalDateTime parse = LocalDateTime.parse("1985-09-23 10:12:22", formatter);
    }

    //获取时间戳
    @Test
    public void test07() {
        Instant now = Instant.now();
        System.out.println(now.getNano());
        //秒
        System.out.println(now.getEpochSecond());
        //毫秒
        System.out.println(now.toEpochMilli());
        System.out.println(System.currentTimeMillis());
    }


    //计算日期时间差类
    //Duration/Period类: 计算日期时间差
    @Test
    public void test08() {
        // Duration计算时间的距离
        LocalTime now = LocalTime.now();
        LocalTime time = LocalTime.of(0, 15, 20);
        LocalTime time1 = LocalTime.of(88, 15, 20);
        Duration duration = Duration.between(time, time1);
        //相差的天数
        System.out.println(duration.toDays());

        // Period计算日期的距离
        LocalDate nowDate = LocalDate.now();
        LocalDate date = LocalDate.of(2023, 7, 21);
        Period period = Period.between(date, nowDate);
        System.out.println(period.getDays());
    }



    //JDK 8的时间校正器
    @Test
    public void test09(){
        LocalDateTime now = LocalDateTime.now();
        TemporalAdjuster temporalAdjuster = temporal->{
            LocalDateTime dateTime = (LocalDateTime) temporal;
            dateTime = dateTime.plusMonths(1).withDayOfMonth(1);
            return dateTime;
        };

        now = now.with(temporalAdjuster);
        System.out.println(now);
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        System.out.println(dateTimeFormatter.format(now));
    }

}
